<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\scanwork\Order;
use app\admin\model\scanwork\Allocation;
use app\admin\model\scanwork\Report;
use app\admin\model\scanwork\Product;
use app\admin\model\scanwork\Config as ConfigModel;
use app\admin\model\scanwork\ProductModel;
use app\admin\model\scanwork\Process;
use think\Db;
use think\Exception;

/**
 * 千牛小程序API控制器
 */
class Qianniu extends Api
{
    protected $noNeedLogin = ['qianniuLogin', 'checkQianniuToken', 'getTodayStats', 'getUserInfo', 'profile', 'getUnreadMessageCount', 'getLatestMessages', 'getReports', 'getActiveReports', 'getTasks'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 千牛小程序登录
     */
    public function qianniuLogin()
    {
        $code = $this->request->post('code');
        $corpId = $this->request->post('corp_id');
        
        if (!$code || !$corpId) {
            $this->error('参数不完整');
        }
        
        try {
            // 开发环境：使用简化的用户信息获取
            $qianniuUserInfo = $this->getQianniuUserInfo($code, $corpId);
            if (!$qianniuUserInfo) {
                $this->error('千牛登录失败');
            }
            
            // 查找或创建用户
            $user = $this->findOrCreateQianniuUser($qianniuUserInfo);
            
            // 生成token
            $token = md5($user->id . time() . rand(1000, 9999));
            
            // 保存千牛用户信息到session
            $sessionData = [
                'user_id' => $user->id,
                'qianniu_user_id' => $qianniuUserInfo['userid'],
                'corp_id' => $corpId,
                'name' => $qianniuUserInfo['name'],
                'department_ids' => $qianniuUserInfo['department_ids'] ?? [],
                'position' => $qianniuUserInfo['position'] ?? ''
            ];
            session('qianniu_user_info', $sessionData);
            session('qianniu_token', $token);
            
            // 同时保存到数据库，作为备用方案
            $user->qianniu_token = $token;
            $user->qianniu_token_expire = time() + 7200; // 2小时过期
            $user->save();
            
            // 调试信息
            file_put_contents('/tmp/qianniu_debug.log', "登录成功 - Token: " . $token . "\n", FILE_APPEND);
            file_put_contents('/tmp/qianniu_debug.log', "Session数据: " . json_encode($sessionData) . "\n", FILE_APPEND);
            
            // 立即验证session是否保存成功
            $savedToken = session('qianniu_token');
            $savedUserInfo = session('qianniu_user_info');
            file_put_contents('/tmp/qianniu_debug.log', "立即验证 - 保存的Token: " . $savedToken . "\n", FILE_APPEND);
            file_put_contents('/tmp/qianniu_debug.log', "立即验证 - 保存的UserInfo: " . json_encode($savedUserInfo) . "\n", FILE_APPEND);
            
            $this->success('登录成功', [
                'token' => $token,
                'user_info' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'qianniu_user_id' => $qianniuUserInfo['userid'],
                    'name' => $qianniuUserInfo['name'],
                    'is_admin' => false  // 千牛小程序用户默认为员工
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取千牛用户信息
     */
    private function getQianniuUserInfo($code, $corpId)
    {
        // 从配置文件获取千牛应用配置
        $qianniuConfig = config('qianniu');
        $appId = $qianniuConfig['app_id'];
        $clientId = $qianniuConfig['app_key'];
        $clientSecret = $qianniuConfig['app_secret'];
        
        try {
            // 调用千牛API获取用户信息
            $url = "https://open.dingtalk.com/api/auth/userinfo";
            $data = [
                'access_token' => $this->getAccessToken($clientId, $clientSecret),
                'code' => $code
            ];
            
            $response = $this->httpPost($url, $data);
            $result = json_decode($response, true);
            
            if (isset($result['userid'])) {
                return [
                    'userid' => $result['userid'],
                    'name' => $result['name'] ?? '千牛用户',
                    'department_ids' => $result['department_ids'] ?? [1],
                    'position' => $result['position'] ?? '员工'
                ];
            }
        } catch (Exception $e) {
            // 如果API调用失败，继续执行下面的模拟数据返回
        }
        
        // 如果API调用失败或没有userid，返回模拟数据
        return [
            'userid' => 'qianniu_' . substr(md5($code), 0, 8),
            'name' => '千牛用户',
            'department_ids' => [1, 2],
            'position' => '员工'
        ];
    }
    
    /**
     * 获取千牛访问令牌
     */
    private function getAccessToken($clientId, $clientSecret)
    {
        $url = "https://open.dingtalk.com/api/auth/getAccessToken";
        $data = [
            'appkey' => $clientId,
            'appsecret' => $clientSecret
        ];
        
        $response = $this->httpPost($url, $data);
        $result = json_decode($response, true);
        
        return $result['access_token'] ?? '';
    }
    
    /**
     * HTTP POST请求
     */
    private function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }

    /**
     * 查找或创建千牛用户
     */
    private function findOrCreateQianniuUser($qianniuUserInfo)
    {
        $user = User::where('qianniu_user_id', $qianniuUserInfo['userid'])->find();
        
        if (!$user) {
            $userData = [
                'username' => 'qn_' . $qianniuUserInfo['userid'],
                'nickname' => $qianniuUserInfo['name'],
                'qianniu_user_id' => $qianniuUserInfo['userid'],
                'openid' => 'qianniu_' . $qianniuUserInfo['userid'], // 为千牛用户设置特殊的openid
                'wechat_openid' => 'qianniu_wechat_' . $qianniuUserInfo['userid'] . '_' . time() . '_' . rand(1000, 9999), // 为千牛用户设置唯一的wechat_openid
                'status' => 'normal',
                'createtime' => time()
            ];
            $user = User::create($userData);
        }
        
        return $user;
    }

    /**
     * 验证千牛token
     */
    public function checkQianniuToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }
        
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        $sessionToken = session('qianniu_token');
        $qianniuUserInfo = session('qianniu_user_info');
        
        // 调试信息
        file_put_contents('/tmp/qianniu_debug.log', "验证token - 请求token: " . $token . "\n", FILE_APPEND);
        file_put_contents('/tmp/qianniu_debug.log', "验证token - Session token: " . $sessionToken . "\n", FILE_APPEND);
        file_put_contents('/tmp/qianniu_debug.log', "验证token - Session userInfo: " . json_encode($qianniuUserInfo) . "\n", FILE_APPEND);
        
        // 检查token是否匹配且用户信息存在
        if ($token !== $sessionToken || !$qianniuUserInfo) {
            // Session验证失败，尝试从数据库验证
            $user = User::where('qianniu_token', $token)
                       ->where('qianniu_token_expire', '>', time())
                       ->find();
            if (!$user) {
                $this->error('token无效或已过期');
            }
            
            // 从数据库获取用户信息
            $qianniuUserInfo = [
                'user_id' => $user->id,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname
            ];
        } else {
            // Session验证成功，验证用户是否仍然存在
            $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
            if (!$user) {
                $this->error('用户不存在');
            }
        }
        
        $this->success('token有效', [
            'user_info' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'qianniu_user_id' => $qianniuUserInfo['qianniu_user_id'],
                'name' => $qianniuUserInfo['name'],
                'is_admin' => false
            ]
        ]);
    }

    /**
     * 验证千牛token并返回用户信息
     */
    private function validateQianniuToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }
        
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        $sessionToken = session('qianniu_token');
        $qianniuUserInfo = session('qianniu_user_info');
        
        // 检查token是否匹配且用户信息存在
        if ($token !== $sessionToken || !$qianniuUserInfo) {
            $this->error('token无效或已过期');
        }
        
        // 验证用户是否仍然存在
        $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        return ['user' => $user, 'qianniuUserInfo' => $qianniuUserInfo];
    }

    /**
     * 通用千牛token验证方法 - 支持多种传递方式
     */
    private function validateQianniuTokenMulti()
    {
        $token = null;
        
        // 1. 尝试从Authorization头获取
        $authHeader = $this->request->header('Authorization');
        if ($authHeader) {
            if (strpos($authHeader, 'Bearer ') === 0) {
                $token = substr($authHeader, 7);
            } else {
                $token = $authHeader;
            }
        }
        
        // 2. 尝试从X-Auth-Token头获取
        if (!$token) {
            $token = $this->request->header('X-Auth-Token');
        }
        
        // 3. 尝试从token头获取
        if (!$token) {
            $token = $this->request->header('token');
        }
        
        // 4. 尝试从Token头获取（大写T）
        if (!$token) {
            $token = $this->request->header('Token');
        }
        
        // 5. 尝试从请求体获取
        if (!$token) {
            $token = $this->request->post('token');
        }
        
        // 6. 尝试从GET参数获取
        if (!$token) {
            $token = $this->request->get('token');
        }
        
        if (!$token) {
            $this->error('未提供token');
        }
        
        // 优先使用数据库验证token
        $user = User::where('qianniu_token', $token)
                   ->where('qianniu_token_expire', '>', time())
                   ->find();
        if (!$user) {
            $this->error('token无效或已过期');
        }
        
        // 从数据库获取用户信息
        $qianniuUserInfo = [
            'user_id' => $user->id,
            'qianniu_user_id' => $user->qianniu_user_id,
            'name' => $user->nickname
        ];
        
        return ['user' => $user, 'qianniuUserInfo' => $qianniuUserInfo];
    }

    /**
     * 获取我的分工任务（员工端）
     */
    public function getMyAllocations()
    {
        $qianniuUserInfo = session('qianniu_user_info');
        if (!$qianniuUserInfo) {
            $this->error('用户未登录');
        }
        
        $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = ['user_id' => $user->id];
        if ($status !== '') {
            $where['status'] = $status;
        }
        
        $list = Allocation::with(['order', 'model.product', 'process'])
            ->where($where)
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
            
        $this->success('获取成功', [
            'total' => $list->total(),
            'list' => $list->items()
        ]);
    }

    /**
     * 提交报工（员工端）
     */
    public function submitReport()
    {
        $qianniuUserInfo = session('qianniu_user_info');
        if (!$qianniuUserInfo) {
            $this->error('用户未登录');
        }
        
        $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $allocationId = $this->request->post('allocation_id');
        $itemNos = $this->request->post('item_nos/a', []);
        $workType = $this->request->post('work_type', 'piece');
        $workHours = floatval($this->request->post('work_hours', 0));
        $remark = $this->request->post('remark', '');
        
        if (empty($allocationId)) {
            $this->error('分工ID不能为空');
        }
        
        $allocation = Allocation::where(['id' => $allocationId, 'user_id' => $user->id])->find();
        if (!$allocation) {
            $this->error('分工任务不存在');
        }
        
        $exists = Report::where('allocation_id', $allocationId)->find();
        if ($exists) {
            $this->error('该任务已报工');
        }
        
        Db::startTrans();
        try {
            $wage = 0;
            if ($allocation->work_type == 'piece') {
                $wage = count($itemNos) * $allocation->piece_price;
            } else {
                $wage = $workHours * $allocation->time_price;
            }
            
            $reportData = [
                'allocation_id' => $allocationId,
                'user_id' => $user->id,
                'quantity' => count($itemNos),
                'work_hours' => $workHours,
                'wage' => $wage,
                'remark' => $remark,
                'item_nos' => json_encode($itemNos),
                'status' => 0,
                'createtime' => time()
            ];
            
            $report = Report::create($reportData);
            
            $allocation->status = 1;
            $allocation->save();
            
            Db::commit();
            $this->success('报工成功', $report);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('报工失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单列表（管理员端）
     */
    public function getOrders()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $list = Order::with(['orderModels.model.product'])
            ->where($where)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total()
        ]);
    }

    /**
     * 创建分工任务（管理员端）
     */
    public function createAllocation()
    {
        $orderId = $this->request->post('order_id');
        $modelId = $this->request->post('model_id');
        $processId = $this->request->post('process_id');
        $userId = $this->request->post('user_id');
        $quantity = $this->request->post('quantity');
        $workType = $this->request->post('work_type', 'piece');
        
        if (!$orderId || !$modelId || !$processId || !$userId || !$quantity) {
            $this->error('参数不完整');
        }
        
        Db::startTrans();
        try {
            $data = [
                'order_id' => $orderId,
                'model_id' => $modelId,
                'process_id' => $processId,
                'user_id' => $userId,
                'quantity' => $quantity,
                'work_type' => $workType,
                'status' => 0,
                'createtime' => time()
            ];
            
            $allocation = Allocation::create($data);
            
            Db::commit();
            $this->success('分工任务创建成功', $allocation);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 审核报工（管理员端）
     */
    public function auditReport()
    {
        $reportId = $this->request->post('report_id');
        $status = $this->request->post('status');
        $auditReason = $this->request->post('audit_reason', '');
        
        if (!$reportId || !in_array($status, ['1', '2'])) {
            $this->error('参数错误');
        }
        
        $report = Report::get($reportId);
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        Db::startTrans();
        try {
            $report->status = $status;
            if ($status == '2') {
                $report->audit_reason = $auditReason;
            }
            
            $qianniuUserInfo = session('qianniu_user_info');
            $report->audit_user_id = $qianniuUserInfo['user_id'] ?? 1;
            $report->audit_time = time();
            
            $report->save();
            
            Db::commit();
            $this->success('审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取产品列表
     */
    public function getProducts()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['name|code', 'like', '%' . $keyword . '%'];
        }
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Product::where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            // 获取型号数量
            $item['modelCount'] = \app\admin\model\scanwork\ProductModel::where('product_id', $item['id'])->count();
            // 获取订单数量
            $item['orderCount'] = Order::where('product_id', $item['id'])->count();
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 更新产品状态
     */
    public function updateProductStatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        
        if (!$id || !in_array($status, [0, 1])) {
            $this->error('参数错误');
        }
        
        $product = Product::get($id);
        if (!$product) {
            $this->error('产品不存在');
        }
        
        $product->status = $status;
        $product->save();
        
        $this->success('更新成功');
    }

    /**
     * 获取工序列表
     */
    public function getProcesses()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['name|code', 'like', '%' . $keyword . '%'];
        }
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Process::where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            // 获取分配次数
            $item['allocationCount'] = Allocation::where('process_id', $item['id'])->count();
            // 获取完成次数
            $item['completedCount'] = Report::where('allocation.process_id', $item['id'])->where('status', 1)->count();
            // 获取平均工时
            $avgHours = Report::where('allocation.process_id', $item['id'])->where('status', 1)->avg('work_hours');
            $item['avgHours'] = round($avgHours, 2);
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 更新工序状态
     */
    public function updateProcessStatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        
        if (!$id || !in_array($status, [0, 1])) {
            $this->error('参数错误');
        }
        
        $process = Process::get($id);
        if (!$process) {
            $this->error('工序不存在');
        }
        
        $process->status = $status;
        $process->save();
        
        $this->success('更新成功');
    }

    /**
     * 获取用户统计
     */
    public function getUserStats()
    {
        $total = User::count();
        $admin = User::where('role', 'admin')->count();
        $employee = User::where('role', 'employee')->count();
        
        $this->success('获取成功', [
            'total' => $total,
            'admin' => $admin,
            'employee' => $employee
        ]);
    }

    /**
     * 获取用户列表
     */
    public function getUsers()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $keyword = $this->request->get('keyword', '');
        $role = $this->request->get('role', '');
        
        $where = [];
        if ($keyword) {
            $where[] = ['nickname|username', 'like', '%' . $keyword . '%'];
        }
        if ($role) {
            $where[] = ['role', '=', $role];
        }
        
        $list = User::where($where)
            ->field('id,nickname,username,avatar,employee_no,qianniu_user_id,role,status,department,createtime')
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total()
        ]);
    }

    /**
     * 更新用户状态
     */
    public function updateUserStatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        
        if (!$id || !in_array($status, [0, 1])) {
            $this->error('参数错误');
        }
        
        $user = User::get($id);
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $user->status = $status === 1 ? 'normal' : 'hidden';
        $user->save();
        
        $this->success('更新成功');
    }

    /**
     * 获取用户详情
     */
    public function getUserDetail()
    {
        $id = $this->request->get('id');
        
        if (!$id) {
            $this->error('参数错误');
        }
        
        $user = User::where('id', $id)->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $this->success('获取成功', $user);
    }

    /**
     * 创建用户
     */
    public function createUser()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $nickname = $this->request->post('nickname');
        $employeeNo = $this->request->post('employee_no');
        $department = $this->request->post('department');
        $role = $this->request->post('role', 'employee');
        $status = $this->request->post('status', 'normal');
        
        if (!$username || !$password || !$nickname) {
            $this->error('必填字段不能为空');
        }
        
        // 检查用户名是否已存在
        $exists = User::where('username', $username)->find();
        if ($exists) {
            $this->error('用户名已存在');
        }
        
        $userData = [
            'username' => $username,
            'password' => md5($password),
            'nickname' => $nickname,
            'employee_no' => $employeeNo,
            'department' => $department,
            'role' => $role,
            'status' => $status,
            'createtime' => time()
        ];
        
        $user = User::create($userData);
        $this->success('创建成功', $user);
    }

    /**
     * 更新用户
     */
    public function updateUser()
    {
        $id = $this->request->post('id');
        $nickname = $this->request->post('nickname');
        $employeeNo = $this->request->post('employee_no');
        $department = $this->request->post('department');
        $role = $this->request->post('role', 'employee');
        $status = $this->request->post('status', 'normal');
        $qianniuUserId = $this->request->post('qianniu_user_id');
        
        if (!$id || !$nickname) {
            $this->error('参数错误');
        }
        
        $user = User::get($id);
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $user->nickname = $nickname;
        $user->employee_no = $employeeNo;
        $user->department = $department;
        $user->role = $role;
        $user->status = $status;
        $user->qianniu_user_id = $qianniuUserId;
        $user->save();
        
        $this->success('更新成功');
    }

    /**
     * 上传图片
     */
    public function uploadImage()
    {
        $file = $this->request->file('image');
        
        if (!$file) {
            $this->error('没有接收到文件');
        }
        
        $info = $file->validate(['size' => 10240 * 1024, 'ext' => 'jpg,jpeg,png,gif'])
            ->move('uploads/qianniu/');
            
        if (!$info) {
            $this->error('图片上传失败：' . $file->getError());
        }
        
        $filename = $info->getSaveName();
        $url = request()->domain() . '/uploads/qianniu/' . $filename;
        
        $this->success('上传成功', ['url' => $url]);
    }

    /**
     * 获取主动报工统计
     */
    public function getActiveReportStats()
    {
        $pending = Report::where('status', 0)->count();
        $approved = Report::where('status', 1)->count();
        $rejected = Report::where('status', 2)->count();
        
        $this->success('获取成功', [
            'pending' => $pending,
            'approved' => $approved,
            'rejected' => $rejected
        ]);
    }

    /**
     * 获取主动报工列表
     */
    public function getActiveReports()
    {
        // 使用通用token验证方法
        $result = $this->validateQianniuTokenMulti();
        $user = $result['user'];
        $qianniuUserInfo = $result['qianniuUserInfo'];

        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('page_size', 20);
        $status = $this->request->get('status', '');
        
        $where = [];
        if ($status !== '') {
            $where[] = ['status', '=', intval($status)];
        }
        
        $list = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where($where)
            ->order('id desc')
            ->paginate($pageSize, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['statusText'] = $this->getReportStatusText($item['status']);
        }
        
        $this->success('获取成功', [
            'list' => $items,
            'total' => $list->total()
        ]);
    }

    /**
     * 获取主动报工详情
     */
    public function getActiveReportDetail()
    {
        $id = $this->request->get('id');
        
        if (!$id) {
            $this->error('参数错误');
        }
        
        $report = Report::with(['user', 'allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where('id', $id)
            ->find();
        
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        $report['statusText'] = $this->getReportStatusText($report['status']);
        
        $this->success('获取成功', $report);
    }

    /**
     * 审核主动报工
     */
    public function auditActiveReport()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        $remark = $this->request->post('remark', '');
        
        if (!$id || !in_array($status, [1, 2])) {
            $this->error('参数错误');
        }
        
        $report = Report::get($id);
        if (!$report) {
            $this->error('报工记录不存在');
        }
        
        if ($report['status'] != 0) {
            $this->error('该报工记录已审核');
        }
        
        Db::startTrans();
        try {
            $report->status = $status;
            $report->audit_reason = $remark;
            
            $qianniuUserInfo = session('qianniu_user_info');
            $report->audit_user_id = $qianniuUserInfo['user_id'] ?? 1;
            $report->audit_time = time();
            
            $report->save();
            
            Db::commit();
            $this->success('审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取报工状态文本
     */
    private function getReportStatusText($status)
    {
        $statusMap = [
            0 => '待审核',
            1 => '已通过',
            2 => '已拒绝'
        ];
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 获取概览统计
     */
    public function getOverviewStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $totalOrders = Order::where($where)->count();
        $totalUsers = User::where('status', 'normal')->count();
        $totalReports = Report::where($where)->count();
        $totalWage = Report::where($where)->sum('wage');
        
        $this->success('获取成功', [
            'totalOrders' => $totalOrders,
            'totalUsers' => $totalUsers,
            'totalReports' => $totalReports,
            'totalWage' => round($totalWage, 2)
        ]);
    }

    /**
     * 获取报工统计
     */
    public function getReportStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $pending = Report::where($where)->where('status', 0)->count();
        $approved = Report::where($where)->where('status', 1)->count();
        $rejected = Report::where($where)->where('status', 2)->count();
        $avgHours = Report::where($where)->where('status', 1)->avg('work_hours');
        
        $this->success('获取成功', [
            'pending' => $pending,
            'approved' => $approved,
            'rejected' => $rejected,
            'avgHours' => round($avgHours, 2)
        ]);
    }

    /**
     * 获取用户活跃度
     */
    public function getUserActivity()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $limit = $this->request->get('limit', 10);
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['user'])
            ->where($where)
            ->where('status', 1)
            ->group('user_id')
            ->field('user_id, COUNT(*) as reportCount, SUM(work_hours) as totalHours, SUM(wage) as totalWage')
            ->order('reportCount desc')
            ->limit($limit)
            ->select();
        
        foreach ($list as &$item) {
            $item['user_id'] = $item['user_id'];
            $item['reportCount'] = intval($item['reportCount']);
            $item['totalHours'] = round($item['totalHours'], 2);
            $item['totalWage'] = round($item['totalWage'], 2);
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取产品统计
     */
    public function getProductStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['allocation.model.product'])
            ->where($where)
            ->group('allocation.model_id')
            ->field('allocation.model_id, COUNT(*) as reportCount')
            ->select();
        
        foreach ($list as &$item) {
            $modelId = $item['allocation']['model_id'];
            $orderCount = Order::where($where)->where('model_id', $modelId)->count();
            $completionRate = $orderCount > 0 ? round(($item['reportCount'] / $orderCount) * 100, 2) : 0;
            
            $item['product_name'] = $item['allocation']['model']['product']['name'] ?? '未知产品';
            $item['model_name'] = $item['allocation']['model']['name'] ?? '未知型号';
            $item['orderCount'] = $orderCount;
            $item['completionRate'] = $completionRate;
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取工序统计
     */
    public function getProcessStats()
    {
        $timeRange = $this->request->get('time_range', 'month');
        $where = $this->getTimeWhere($timeRange);
        
        $list = Report::with(['allocation.process'])
            ->where($where)
            ->group('allocation.process_id')
            ->field('allocation.process_id, COUNT(*) as completedCount, AVG(work_hours) as avgHours')
            ->select();
        
        foreach ($list as &$item) {
            $processId = $item['allocation']['process_id'];
            $allocationCount = Allocation::where($where)->where('process_id', $processId)->count();
            
            $item['process_name'] = $item['allocation']['process']['name'] ?? '未知工序';
            $item['description'] = $item['allocation']['process']['description'] ?? '';
            $item['allocationCount'] = $allocationCount;
            $item['avgHours'] = round($item['avgHours'], 2);
        }
        
        $this->success('获取成功', $list);
    }

    /**
     * 获取时间条件
     */
    private function getTimeWhere($timeRange)
    {
        $now = time();
        $where = [];
        
        switch ($timeRange) {
            case 'today':
                $startTime = strtotime(date('Y-m-d 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'week':
                $startTime = strtotime('monday this week');
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'month':
                $startTime = strtotime(date('Y-m-01 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
            case 'year':
                $startTime = strtotime(date('Y-01-01 00:00:00'));
                $where[] = ['createtime', '>=', $startTime];
                break;
        }
        
        return $where;
    }

    /**
     * 提交主动报工
     */
    public function submitActiveReport()
    {
        $qianniuUserInfo = session('qianniu_user_info');
        if (!$qianniuUserInfo) {
            $this->error('用户未登录');
        }
        
        $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        
        $orderNo = $this->request->post('order_no');
        $productId = $this->request->post('product_id');
        $processId = $this->request->post('process_id');
        $quantity = intval($this->request->post('quantity'));
        $workHours = floatval($this->request->post('work_hours'));
        $remark = $this->request->post('remark', '');
        $images = $this->request->post('images/a', []);
        
        if (!$orderNo || !$productId || !$processId || !$quantity || !$workHours) {
            $this->error('必填字段不能为空');
        }
        
        // 检查产品是否存在
        $product = Product::get($productId);
        if (!$product) {
            $this->error('产品不存在');
        }
        
        // 检查工序是否存在
        $process = Process::get($processId);
        if (!$process) {
            $this->error('工序不存在');
        }
        
        Db::startTrans();
        try {
            // 计算工资
            $wage = 0;
            if ($process->work_type == 'piece') {
                $wage = $quantity * $process->piece_price;
            } else {
                $wage = $workHours * $process->time_price;
            }
            
            $reportData = [
                'user_id' => $user->id,
                'order_no' => $orderNo,
                'product_id' => $productId,
                'process_id' => $processId,
                'quantity' => $quantity,
                'work_hours' => $workHours,
                'wage' => $wage,
                'remark' => $remark,
                'images' => json_encode($images),
                'status' => 0, // 待审核
                'createtime' => time()
            ];
            
            $report = Report::create($reportData);
            
            Db::commit();
            $this->success('提交成功', $report);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败：' . $e->getMessage());
        }
    }

    /**
     * 获取今日统计
     */
    public function getTodayStats()
    {
        // 使用通用token验证方法
        $result = $this->validateQianniuTokenMulti();
        $user = $result['user'];
        $qianniuUserInfo = $result['qianniuUserInfo'];
        
        file_put_contents('/tmp/qianniu_debug.log', "getTodayStats - 数据库验证成功，用户ID: " . $user->id . "\n", FILE_APPEND);
        
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $taskCount = Allocation::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->count();
        
        // 今日报工数
        $reportCount = Report::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->count();
        
        // 今日工资
        $wage = Report::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->where('status', 1) // 已审核
            ->sum('wage');
        
        $this->success('获取成功', [
            'todayTaskCount' => $taskCount,
            'todayReportCount' => $reportCount,
            'todayWage' => $wage
        ]);
    }

    /**
     * 获取最新消息
     */
    public function getLatestMessages()
    {
        // 使用通用token验证方法
        $result = $this->validateQianniuTokenMulti();
        $user = $result['user'];
        $qianniuUserInfo = $result['qianniuUserInfo'];

        $limit = $this->request->get('limit', 10);
        
        // 这里可以根据实际需求实现消息系统
        // 暂时返回模拟数据
        $messages = [
            [
                'id' => 1,
                'title' => '系统通知',
                'content' => '欢迎使用工厂报工系统',
                'type' => 'system',
                'createtime' => time()
            ]
        ];
        
        $this->success('获取成功', $messages);
    }

    /**
     * 获取任务列表
     */
    public function getTasks()
    {
        // 使用通用token验证方法
        $result = $this->validateQianniuTokenMulti();
        $user = $result['user'];
        $qianniuUserInfo = $result['qianniuUserInfo'];
        
        $allocations = Allocation::with(['order', 'model', 'process'])
            ->where('user_id', $user->id)
            ->where('status', 0) // 未完成
            ->order('createtime desc')
            ->select();
        
        $tasks = [];
        foreach ($allocations as $allocation) {
            $tasks[] = [
                'id' => $allocation->id,
                'order_no' => $allocation->order ? $allocation->order->order_no : '',
                'model_name' => $allocation->model ? $allocation->model->name : '',
                'process_name' => $allocation->process ? $allocation->process->name : '',
                'quantity' => $allocation->quantity,
                'createtime' => $allocation->createtime
            ];
        }
        
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取报工列表（管理员用）
     */
    public function getReports()
    {
        // 使用通用token验证方法
        $result = $this->validateQianniuTokenMulti();
        $user = $result['user'];
        $qianniuUserInfo = $result['qianniuUserInfo'];
        
        $status = $this->request->get('status');
        $limit = $this->request->get('limit', 20);
        $page = $this->request->get('page', 1);
        
        $where = [];
        if ($status !== null && $status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $reports = Report::with(['user', 'allocation.order', 'allocation.model', 'allocation.process'])
            ->where($where)
            ->order('createtime desc')
            ->page($page, $limit)
            ->select();
        
        $total = Report::where($where)->count();
        
        $list = [];
        foreach ($reports as $report) {
            $list[] = [
                'id' => $report->id,
                'user_name' => $report->user ? $report->user->nickname : '',
                'order_no' => $report->allocation && $report->allocation->order ? $report->allocation->order->order_no : '',
                'model_name' => $report->allocation && $report->allocation->model ? $report->allocation->model->name : '',
                'process_name' => $report->allocation && $report->allocation->process ? $report->allocation->process->name : '',
                'quantity' => $report->quantity,
                'wage' => $report->wage,
                'status' => $report->status,
                'status_text' => $this->getReportStatusText($report->status),
                'createtime' => $report->createtime
            ];
        }
        
        $this->success('获取成功', [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        // 验证千牛token
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $sessionToken = session('qianniu_token');
        $qianniuUserInfo = session('qianniu_user_info');

        // 检查token是否匹配且用户信息存在
        if ($token !== $sessionToken || !$qianniuUserInfo) {
            // Session验证失败，尝试从数据库验证
            $user = User::where('qianniu_token', $token)
                       ->where('qianniu_token_expire', '>', time())
                       ->find();
            if (!$user) {
                $this->error('token无效或已过期');
            }

            // 从数据库获取用户信息
            $qianniuUserInfo = [
                'user_id' => $user->id,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname
            ];
        } else {
            // Session验证成功，验证用户是否仍然存在
            $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
            if (!$user) {
                $this->error('用户不存在');
            }
        }
        
        $userInfo = [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'qianniu_user_id' => $qianniuUserInfo['qianniu_user_id'],
            'name' => $qianniuUserInfo['name'],
            'is_admin' => false, // 千牛小程序用户默认为员工
            'department_ids' => $qianniuUserInfo['department_ids'] ?? [],
            'position' => $qianniuUserInfo['position'] ?? ''
        ];
        
        $this->success('获取成功', $userInfo);
    }

    /**
     * 获取用户个人资料统计
     */
    public function profile()
    {
        // 验证千牛token
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $sessionToken = session('qianniu_token');
        $qianniuUserInfo = session('qianniu_user_info');

        // 检查token是否匹配且用户信息存在
        if ($token !== $sessionToken || !$qianniuUserInfo) {
            // Session验证失败，尝试从数据库验证
            $user = User::where('qianniu_token', $token)
                       ->where('qianniu_token_expire', '>', time())
                       ->find();
            if (!$user) {
                $this->error('token无效或已过期');
            }

            // 从数据库获取用户信息
            $qianniuUserInfo = [
                'user_id' => $user->id,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname
            ];
        } else {
            // Session验证成功，验证用户是否仍然存在
            $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
            if (!$user) {
                $this->error('用户不存在');
            }
        }
        
        // 统计用户的任务数量
        $totalTasks = Allocation::where('user_id', $user->id)->count();
        
        // 统计用户的报工数量
        $totalReports = Report::where('user_id', $user->id)->count();
        
        // 统计用户的总工资
        $totalWage = Report::where('user_id', $user->id)
            ->where('status', 1) // 已审核
            ->sum('wage');
        
        $stats = [
            'totalTasks' => $totalTasks,
            'totalReports' => $totalReports,
            'totalWage' => $totalWage
        ];
        
        $this->success('获取成功', $stats);
    }

    /**
     * 获取未读消息数量
     */
    public function getUnreadMessageCount()
    {
        // 验证千牛token
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $sessionToken = session('qianniu_token');
        $qianniuUserInfo = session('qianniu_user_info');

        // 检查token是否匹配且用户信息存在
        if ($token !== $sessionToken || !$qianniuUserInfo) {
            // Session验证失败，尝试从数据库验证
            $user = User::where('qianniu_token', $token)
                       ->where('qianniu_token_expire', '>', time())
                       ->find();
            if (!$user) {
                $this->error('token无效或已过期');
            }

            // 从数据库获取用户信息
            $qianniuUserInfo = [
                'user_id' => $user->id,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname
            ];
        } else {
            // Session验证成功，验证用户是否仍然存在
            $user = User::where('qianniu_user_id', $qianniuUserInfo['qianniu_user_id'])->find();
            if (!$user) {
                $this->error('用户不存在');
            }
        }
        
        // 这里可以根据实际的消息表来统计未读消息数量
        // 暂时返回0，表示没有未读消息
        $unreadCount = 0;
        
        $this->success('获取成功', ['count' => $unreadCount]);
    }
}